<script setup lang="ts">
import type { FileTableItem, fileTypeStr } from "@/common/apis/train/type"
import type { TabsPaneContext } from "element-plus"
import { clearTaskProcessFileApi, deleteTaskApi, downloadTaskProcessFileApi, saveFileApi, searchTaskFileApi } from "@/common/apis/train"
import { usePagination } from "@/common/composables/usePagination"
import { downloadFile } from "@/common/utils/fileUtils"
import { Search } from "@element-plus/icons-vue"
import { debounce } from "lodash-es"
import { defineProps, onActivated, onMounted, ref, watch } from "vue"


const props = defineProps<Props>()

const { paginationData, handleSizeChange, handleCurrentChange } = usePagination()

interface Props {
  taskStatus: number | undefined
}
let timer: number | null = null
const route = useRoute()
const taskStatus = ref<number | undefined>(props.taskStatus)
const searchKey = ref<string>()
// 文件列表类型
const fileType = ref<fileTypeStr>("agent")
const loading = ref<boolean>(false)
const tableData = ref<FileTableItem[]>([])
const multipleSelection = ref<FileTableItem[]>([])
const TableRef = ref()
const taskId = ref<string>(route.query.id as string)

// 一键删除
function handleCutOff() {
  clearTaskProcessFileApi(taskId.value, "all")
    .then(() => {
      ElMessage.success("一键删除成功")
      handleSearch()
      hanldeClearSelection()
    })
    .catch(() => {
      ElMessage.error("一键删除失败")
    })
}
// 批量下载
async function handleDownloadAll() {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要下载的文件")
    return
  }
  handleDownload(multipleSelection.value)
}
// 下载
function handleDownload(row: FileTableItem[]) {
  const ids: string[] = row.map(r => r.file_id as string)
  downloadTaskProcessFileApi(taskId.value, {
    process_file_ids: ids,
    format: "txt"
  }).then((res) => {
    downloadFile(res)
  })
}
function handleTabClick(tab: TabsPaneContext) {
  handleFile(tab.props.name as fileTypeStr)
}

// 切换文件类型
function handleFile(type: fileTypeStr) {
  fileType.value = type
  handleSearch()
  hanldeClearSelection()
}

// 搜索
function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}

const getTableData = debounce(() => {
  loading.value = true
  searchTaskFileApi(taskId.value, {
    name: searchKey.value ? searchKey.value : "",
    type: fileType.value,
    size: paginationData.pageSize,
    current_page: paginationData.currentPage
  })
    .then(({ data }) => {
      tableData.value = data.rows
      paginationData.total = data.total
    })
    .catch((e) => {
      ElMessage.error(e)
    })
    .finally(() => {
      loading.value = false
    })
}, 500)
function handleSelectionChange(val: []) {
  multipleSelection.value = val
}

function handleMultipleDelete() {
  const ids: string[] = []
  const names: string[] = []
  multipleSelection.value.forEach((item) => {
    ids.push(item.file_id as string)
    names.push(item.file_name)
  })
  ElMessageBox.confirm(`正在删除${fileType.value == "agent" ? "智能体" : "样本"}文件：${names.join("，")}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTaskApi(ids).then(() => {
      ElMessage.success("删除成功")
      hanldeClearSelection()
      getTableData()
    })
  })
}
function hanldeClearSelection() {
  nextTick(() => {
    TableRef.value?.clearSelection()
  })
}
function getRowKeys(row: FileTableItem) {
  return row.file_id
}
function changeSwitchSave(row: any) {
  if (!row.save_flag) return // 避免初始化时触发
  saveFileApi(taskId.value, {
    process_file_id: row.file_id,
    associate_id: row.associate_id
  }).then(() => {
    ElMessage.success("保存成功")
  })
}

onActivated(() => {
  if (taskId.value && taskId.value !== route.query.id) {
    handleSearch()
  }
})

watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

watch(
  () => props.taskStatus,
  () => {
    taskStatus.value = props.taskStatus
    if (taskStatus.value == 1) {
      handleSearch()
    }
  }
)

function refresh() {
  if (taskStatus.value == 1) {
    handleSearch()
  }
}

function restart() {
  handleSearch()
}

onMounted(() => {
  handleSearch()
  timer = Number(setInterval(refresh, 1000 * 60))
})
onBeforeUnmount(() => {
  timer && clearInterval(timer)
})

defineExpose({ restart })
</script>

<template>
  <div class="content-item">
    <div class="content-item-file">
      <div class="toolbar-wrapper">
        <el-space>
          <el-button type="primary" @click="handleDownloadAll">
            批量下载
          </el-button>
          <el-button type="danger" @click="handleMultipleDelete">
            批量删除
          </el-button>
          <el-button type="danger" @click="handleCutOff">
            一键删除
          </el-button>
        </el-space>
        <div>
          <el-input v-model="searchKey" placeholder="请输入搜索内容" class="csc-search-input" @keydown.enter="handleSearch">
            <template #append>
              <el-button :icon="Search" v-throttle="() => handleSearch()" />
            </template>
          </el-input>
        </div>
      </div>
      <el-tabs v-model="fileType" type="card" class="bac-tabs" stretch @tab-click="handleTabClick">
        <el-tab-pane v-for="item in ['agent', 'sample']" ref="TableRef" :key="item"
          :label="item == 'agent' ? '智能体' : '样本'" :name="item">
          <el-table :data="tableData" row-class-name="table-row" :row-key="getRowKeys" height="400" v-loading="loading"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center" :reserve-selection="true" width="55" />
            <el-table-column prop="file_name" label="文件名" header-align="left" />
            <el-table-column prop="version" label="版本" header-align="left" />
            <el-table-column prop="describe" show-overflow-tooltip label="描述" header-align="left" />
            <el-table-column prop="save_flag" label="是否保存" header-align="left">
              <template #default="scope">
                <el-switch width="50" v-model="scope.row.save_flag" :disabled="scope.row.save_flag === 1" inline-prompt
                  :active-value="1" :inactive-value="0" @change="changeSwitchSave(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column align="center" width="150" label="操作">
              <template #default="scope">
                <el-button type="primary" size="small" @click="handleDownload([scope.row.file_id])">
                  下载
                </el-button>
                <el-button size="small" @click="handleDelete(scope.$index, scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pager-wrapper">
            <el-pagination background layout="total, sizes, ->, prev, pager, next, jumper" :disabled="loading"
              :page-sizes="paginationData.pageSizes" :total="paginationData.total" :page-size="paginationData.pageSize"
              :current-page="paginationData.currentPage" @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.content-item {
  margin-bottom: 0 !important;
}

.content-item-file {
  background: var(--el-bg-color);
  border-radius: 4px 4px 4px 4px;
  padding: var(--main-padding) var(--main-padding) 0 var(--main-padding);
}

.pager-wrapper {
  position: relative !important;
  background-color: #031527;
  width: calc(100%) !important;
}

/* 激活的 tab */
::v-deep .bac-tabs .el-tabs__item.is-active {
  background-color: #409eff !important;
  color: #fff !important;
}
/* 鼠标 hover 到未激活的 tab 上时文字 */
::v-deep .bac-tabs .el-tabs__item:hover {
  color: #409eff; /* 你想要的 hover 文字色 */
}

</style>
